import { Drawer, Input, Select, Button, message } from "antd";
import dayjs from "dayjs";
import { forEach, filter, head, last } from "lodash";
import moment from "moment";
import { useState, forwardRef, useImperativeHandle } from "react";
import { useNavigate } from "react-router-dom";
import { v4 as uuid } from "uuid";

import CalendarComponent from "../Calendar/index";
import { AircraftTailNum, AircraftQuery } from "./home";

import { TaskItem } from "~/components/Home/home";
import { useAnalysisTask } from "~/components/Visualization/store/useTaskState";
import { useAircraftTailNum, useAirline } from "~/hooks/home/use-home-api";
import { formatDate, formatDateTZ } from "~/modules/shared/utils/common";
import { useWorkSpace } from "~/modules/workspace/store/use-workspace";

interface Props {}

const NewAnalysis = (props: Props, ref: any) => {
  const { workSpace, update } = useWorkSpace();
  const tailNumRes: any = useAircraftTailNum();
  const tailNumList: AircraftTailNum[] = tailNumRes?.aircrafts;
  const router = useNavigate();
  const { updateTask } = useAnalysisTask();
  // 抽屉的打开、关闭
  const [open, setOpen] = useState(false);
  // 任务名称
  const [taskName, setTaskName] = useState("");
  // 机尾号
  const [tailNum, setTailNum] = useState("");
  // 飞机id
  const [aircraftId, setAircraftId] = useState("");
  const [taskDate, setTaskDate] = useState<string[]>([]);
  //选择年份
  const [dateYear, setDateYear] = useState(dayjs().format("YYYY"));
  // 选择月份
  const [dateMonth, setDateMonth] = useState(dayjs().format("MM"));
  // 任务id
  const [taskId, setTaskId] = useState("");
  const [taskUuId, setTaskUuId] = useState<string>("");

  const [aircraftQuery, setAircraftQuery] = useState<AircraftQuery>({
    id: "",
    CurrentYear: dateYear,
    CurrentMonth: dateMonth,
  });

  const arlineRes: any = useAirline(aircraftQuery);

  const flight: any[] = arlineRes?.aircraft.flights.map((item: any) => {
    item.date = Number(dayjs(item.takeoffTime).format("DD"));
    item.time = formatDate(item.takeoffTime);
    return item;
  });
  const date = dayjs(aircraftQuery.CurrentMonth).daysInMonth();
  const list: any = [];
  for (let i = 1; i <= date; i++) {
    const data: any = [];
    forEach(flight, (item: any) => {
      if (item.date === i) {
        data.push(item.takeoffTime);
      }
    });
    list.push({ date: formatDate(data[0]), data });
  }
  // 机尾号
  const onTailNoChange = (e: any) => {
    const str: string = filter(tailNumList, (item) => {
      return item.id === e;
    })[0].tailNo;
    setTailNum(str);
    setAircraftId(e);
    const params = {
      id: e,
      CurrentYear: dateYear,
      CurrentMonth: dateMonth,
    };
    setAircraftQuery(params);
  };

  // 日历
  const onDateChange = (year: string, month: string) => {
    setDateYear(year);
    setDateMonth(month);
    const params = {
      id: aircraftId,
      CurrentYear: year,
      CurrentMonth: month,
    };
    setAircraftQuery(params);
  };
  const onSelect = (e: string[]) => {
    setTaskDate(e);
  };

  // 自定义关闭抽屉
  const [drawerType, setDrawerType] = useState("add");
  const onOpen = (type: string, value?: TaskItem) => {
    setDrawerType(type);
    if (type === "edit") {
      setTaskName(value?.name ?? "");
      setTailNum(value?.tailno ?? "");
      setTaskId(value?.id ?? "");
      setAircraftId(value?.aircraftId ?? "");
      // @ts-ignore  todo fix it
      setTaskUuId(value?.uuid ?? uuid());
      setDateYear(moment(value?.start_time).format("YYYY"));
      setDateMonth(moment(value?.start_time).format("MM"));
      const data = {
        id: value?.aircraftId ?? "",
        CurrentYear: moment(value?.start_time).format("YYYY"),
        CurrentMonth: moment(value?.start_time).format("MM"),
      };
      setAircraftQuery(data);
      setTaskDate([
        moment(value?.start_time ?? "")
          .utcOffset(0)
          .format("YYYY-MM-DD"),
        moment(value?.end_time ?? "")
          .utcOffset(0)
          .format("YYYY-MM-DD"),
      ]);
    } else {
      setTaskName("");
      setTailNum("");
      setTaskDate([]);
      setDateYear(moment().format("YYYY"));
      setDateMonth(moment().format("MM"));
      setTaskUuId(uuid());
    }
    setOpen(true);
  };
  // 向父组件暴露关闭抽屉方法
  useImperativeHandle(ref, () => ({
    onOpen,
  }));
  // 关闭抽屉
  const onClose = () => {
    setOpen(false);
  };
  // 取消
  const onCancel = () => {
    setOpen(false);
  };
  // 确定
  const onDefine = () => {
    const flightIds: string[] = [];
    forEach(flight, (m) => {
      if (
        moment(m.time).isBetween(head(taskDate), last(taskDate), null, "[]")
      ) {
        flightIds.push(m.id);
      }
    });
    if (taskName === "") {
      message.error("请输入分析名称！");
    } else if (tailNum === "") {
      message.error("请选择机尾号！");
      1;
    } else {
      const task = {
        id: drawerType === "edit" ? taskId : taskUuId,
        name: taskName,
        startTime: formatDateTZ(taskDate[0]),
        endTime:
          taskDate.length > 1
            ? formatDateTZ(taskDate[1])
            : formatDateTZ(taskDate[0]),
        aircraftId,
        tailno: tailNum,
        flights: flightIds,
        type: drawerType,
        customParams: [],
        taskParams: [],
      };
      updateTask(task);
      workSpace.splitCharts = [];
      update(workSpace);
      setOpen(false);
      router("/visualization");
    }
  };

  return (
    <div>
      <Drawer
        title={drawerType === "edit" ? "编辑分析" : "新建分析"}
        placement="right"
        width="74%"
        closable={false}
        onClose={onClose}
        open={open}
        bodyStyle={{ padding: 16 }}
      >
        <div className="flex justify-between mb-16px">
          <div className="w-45%">
            <span className="color-red">* </span>
            <span>名称</span>
            <Input
              className="w-80%! ml-16px!"
              value={taskName}
              placeholder="请输入"
              disabled={drawerType === "edit"}
              onChange={(e) => setTaskName(e.target.value.trim())}
            />
          </div>
          <div className="w-45%">
            <span className="color-red">* </span>
            <span>机尾号</span>
            <Select
              className="w-80%! ml-16px!"
              value={tailNum}
              defaultValue={tailNum}
              showSearch
              placeholder="请选择"
              disabled={drawerType === "edit"}
              optionFilterProp="label"
              options={tailNumList?.map(
                (item: AircraftTailNum, index: number) => {
                  return { value: item.id, label: item.tailNo };
                }
              )}
              onChange={(e) => onTailNoChange(e)}
              filterOption={(input, option) =>
                (option?.label ?? "")
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </div>
        </div>

        <div style={calendarStyle}>
          <CalendarComponent
            taskDate={taskDate}
            onSelect={onSelect}
            flight={list}
            year={dateYear}
            month={dateMonth}
            date={onDateChange}
          />
        </div>
        <div
          className="right-16px bottom-16px"
          style={{ position: "absolute" }}
        >
          <Button className="w-96px! mr-16px" onClick={() => onCancel()}>
            取消
          </Button>
          <Button className="w-96px!" type="primary" onClick={() => onDefine()}>
            确定
          </Button>
        </div>
      </Drawer>
    </div>
  );
};

export default forwardRef(NewAnalysis);

const calendarStyle = {
  maxHeight: "calc(100vh - 200px)",
};
